package com.chicken.controller;

import com.chicken.dto.model.Orders;
import com.chicken.dto.model.Product;
import com.chicken.dto.model.User;
import com.chicken.pojo.HomePageData;
import com.chicken.pojo.Inject;
import com.chicken.vo.BaseResponseVO;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * @author zewei.wang
 * @date 2018/4/4.
 */
public class AdminController extends Controller{
    public void index(){
        User user = getSessionAttr("user");
        if(user.getRole().equals("ADMIN")){
            render("/admin.html");
        }else
        render("/index.html");
    }

    public void admin(){
        User user = getSessionAttr("user");
        if(user.getRole().equals("ADMIN")){
            render("/admin.html");
        }else
            render("/user.html");
    }

    public void goodList(){
        render("/page/goods/goodList.html");
    }

    public void addProduct(){
        Product product = Inject.injectModel(getRequest(),Product.class);
        Random random = new Random();
        int i = random.nextInt(10) + 1;
        product.setCardImage(i+".jpeg");
        if(product.getId() != null && product.getId() > 0){
            product.update();
        }else {
            product.save();
        }
        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();
        renderJson(responseVO);
    }

    public void getProductList(){

        String searchVal = "";
        if(StringUtils.isNotBlank(getPara("keyword"))){
            searchVal = getPara("keyword");
        }
        Integer pageNum = 1;
        if(getParaToInt("pageNum") != null && getParaToInt("pageNum") > 1){
            pageNum = getParaToInt("pageNum");
        }
        Integer count = Integer.parseInt(Db.queryLong("select count(1) from product u" +
                " where u.name like '%"+searchVal+"%' " ).toString());
        List<User> list = User.dao.find("select u.* from product u "+
                " where u.name like '%"+searchVal+"%' " +
                " order by id desc limit ?,10",(pageNum-1)*10);
        int totalPAge = count%10 == 0?(count/10):(count/10+1);
        Page<User> page = new Page<User>(list,pageNum,10,totalPAge,count);
        BaseResponseVO baseResponseVO = new BaseResponseVO();
        baseResponseVO.setSucced();
        baseResponseVO.setCount(count);
        baseResponseVO.setData(list);
        renderJson(baseResponseVO);
    }

    public void getProduct(){
        Product productList = Product.dao.findFirst("select * from product where id = '"+getPara("id")+"'");
        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();
        responseVO.setData(productList);
        renderJson(responseVO);
    }

    public void delProduct(){
        Product.dao.deleteById(getPara("id"));
        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();
        renderJson(responseVO);
    }

    public void getCountEachMonth(){
        List<Orders> ordersList = Orders.dao.find("select o.id,o.productId,p.name,p.price,sum(o.productCount) as totalCount from o orders " +
                "left join product p on(o.productId = p.id) group by o.productId");
        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();
        responseVO.setData(ordersList);
        renderJson(responseVO);
    }

    public void getHomePageData(){
        int todayOrderCount = Db.queryInt("select count(1) from orders where TO_DAYS(now()) - TO_DAYS(create_time) < 1");
        int userCount = Db.queryInt("select count(1) from user");
        int productCount = Db.queryInt("select count(1) from product");

        HomePageData data = new HomePageData();
        data.setTodayOrderCount(todayOrderCount);
        data.setUserCount(userCount);
        data.setProductCount(productCount);

        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();
        responseVO.setData(data);
        renderJson(responseVO);
    }

    public void upload(){
        UploadFile file = getFile();
        BaseResponseVO responseVO = new BaseResponseVO();
        if(file != null){
            responseVO.setSucced();
            responseVO.setData("/upload/"+file.getFileName());
        }else {
            responseVO.setError();
        }
        renderJson(responseVO);

    }

    public void orderList(){
        String searchVal = "";
        if(StringUtils.isNotBlank(getPara("searchVal"))){
            searchVal = getPara("searchVal");
        }
        Integer pageNum = 1;
        if(getParaToInt("pageNum") != null && getParaToInt("pageNum") > 1){
            pageNum = getParaToInt("pageNum");
        }
        Integer count = Integer.parseInt(Db.queryLong("select count(1) from orders o " +
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                " where u.name like '%"+searchVal+"%' or p.name like '%"+searchVal+"%' " +
                "order by o.totalPrice desc" ).toString());
        List<Orders> list = Orders.dao.find("select o.id,u.name as userName,p.id as productId,p.name as productName,p.price,o.totalPrice,o.address,o.create_time from orders o "+
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                " where u.name like '%"+searchVal+"%' or p.name like '%"+searchVal+"%' " +
                "order by o.totalPrice desc"+" limit ?,10",(pageNum-1)*10);
        int totalPAge = count%10 == 0?(count/10):(count/10+1);
        Page<Orders> page = new Page<Orders>(list,pageNum,10,totalPAge,count);
        BaseResponseVO baseResponseVO = new BaseResponseVO();
        baseResponseVO.setSucced();
        baseResponseVO.setCount(count);
        baseResponseVO.setData(list);
        renderJson(baseResponseVO);
    }

    public void login(){
        User user = Inject.injectModel(getRequest(),User.class);
        System.out.print(getPara("tel"));
        User tableUser = User.dao.findFirst("select * from user where tel = '"+user.getTel()+"' and" +
                " password = '"+user.getPassword()+"'");
        BaseResponseVO responseVO = new BaseResponseVO();
        if(tableUser != null){
            setSessionAttr("user",tableUser);
            responseVO.setData(tableUser);
            responseVO.setSucced();
        }else {
            responseVO.setError();
        }
        renderJson(responseVO);
    }

    public void reg(){
        User user = Inject.injectModel(getRequest(),User.class);
        user.setRole("CUSTOMER");
        user.save();
        setSessionAttr("user",user);
        redirect("/index");
    }

    public void month(){
        String searchVal = "";
        Integer pageNum = 1;
        if(getParaToInt("pageNum") != null && getParaToInt("pageNum") > 1){
            pageNum = getParaToInt("pageNum");
        }
        Integer count = Integer.parseInt(Db.queryLong("select count(1) from orders o " +
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                " where DATE_FORMAT(o.create_time, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') " +
                "group by p.id order by o.totalPrice desc" ).toString());
        List<Orders> list = Orders.dao.find("select o.id,u.name as userName,p.name as productName,p.price,o.totalPrice,o.address,o.create_time from orders o "+
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                " where DATE_FORMAT(o.create_time, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') " +
                "group by p.id order by o.totalPrice desc"+" limit ?,10",(pageNum-1)*10);
        int totalPAge = count%10 == 0?(count/10):(count/10+1);
        Page<Orders> page = new Page<Orders>(list,pageNum,10,totalPAge,count);

        renderJson(page);
    }

    public void userOrderList(){
        User user = getSessionAttr("user");
        Integer pageNum = 1;
        if(getParaToInt("pageNum") != null && getParaToInt("pageNum") > 1){
            pageNum = getParaToInt("pageNum");
        }
        Integer count = Integer.parseInt(Db.queryLong("select count(1) from orders o " +
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                " where u.id = " +user.getId()+
                " order by o.totalPrice desc" ).toString());
        List<Orders> list = Orders.dao.find("select o.id,u.name as userName,p.name as productName,p.price,o.totalPrice,o.address,o.create_time from orders o "+
                "left join user u on(o.userId  = u.id) " +
                "left join product p on(o.productId  = p.id) " +
                        " where u.id = " +user.getId()+
                " order by o.totalPrice desc"+" limit ?,10",(pageNum-1)*10);
        int totalPAge = count%10 == 0?(count/10):(count/10+1);
        Page<Orders> page = new Page<Orders>(list,pageNum,10,totalPAge,count);

        renderJson(page);
    }

    public void buy(){
        User user = getSessionAttr("user");
        BaseResponseVO baseResponseVO = new BaseResponseVO();
        if(user == null){
            baseResponseVO.setError();
            baseResponseVO.setMessage("请先登录");
        }
        else {
            Product product = Product.dao.findById(getParaToInt("productId"));
            Orders orders = new Orders();
            orders.setProductId(getParaToInt("productId"));
            orders.setUserId(user.getId());
            orders.setStatus("1");
            Random random = new Random();
            int count = random.nextInt(10)+1;
            BigDecimal price = product.getPrice();
            orders.setTotalPrice(BigDecimal.valueOf(count*Double.parseDouble(price.toString())));
            orders.setAddress(getPara("address"));
            orders.save();
            baseResponseVO.setSucced();
        }
        renderJson(baseResponseVO);
    }

    public void userList(){
        List<User> userList = User.dao.find("select * from user");
        BaseResponseVO baseResponseVO = new BaseResponseVO();
        baseResponseVO.setSucced();
        baseResponseVO.setCount(userList.size());
        baseResponseVO.setData(userList);
        renderJson(baseResponseVO);
    }

    public void userDel(){
        String userID = getPara("newsId");
        User.dao.deleteById(userID);
        BaseResponseVO responseVO = new BaseResponseVO();
        responseVO.setSucced();;
        renderJson(responseVO);
    }


}
